﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Collections;
using FlexiCommerce.Components;
using FlexiCommerce.Collections;

namespace FlexiCommerce.Web.UI
{
    public class QueryDataSourceView<T> : ItemDataSourceView where T: PersistenceItem
    {
        #region Constructors
        public QueryDataSourceView(Engine.IEngine engine, IDataSource owner, string viewName, IQueryable<T> query)
            : base(engine, owner, viewName)
        {
            this.query = query;
        }
        #endregion

        #region Private Members
        private IQueryable<T> query;
        #endregion

        #region Properties
        public IQueryable<T> Query
        {
            get { return query; }
            set { query = value; }
        }

        #endregion

        #region Methods
        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments)
        {
            if (this.Query != null)
            {
                ItemDataSourceSelectingEventArgs selectingArgs = new ItemDataSourceSelectingEventArgs(arguments);
                OnSelecting(selectingArgs);

                IList<T> items = query.Skip(arguments.StartRowIndex).Take(arguments.MaximumRows).ToList<T>();

                Collections.ItemListEventArgs args = new ItemListEventArgs(new Collections.ItemList(items as IEnumerable<PersistenceItem>));
                OnSelected(args);
                return args.Items;
            }
            else
                return null;
        }
        #endregion
    }
}
